/*
 * $Id: utilities.js 42 2013-04-17 15:33:59Z gabakyan $
 * $Author: gabakyan $
 * $Revision: 42 $
 * $Date: 2013-04-17 15:33:59 +0000 (Wed, 17 Apr 2013) $
 *
 * Copyright (c) 2013 Supply Chain Intelligence (SCI), Inc.
 * http://www.scintelligence.com/, Email: info@scintelligence.com
 * All rights reserved.
 *
 * This file is part of Logistics Map.
 *
 * Logistics Map is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, version 3 of the License.
 *
 * Logistics Map is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Logistics Map.  If not, see <http://www.gnu.org/licenses/>.
 */

com.sci.logisticsmap.utilities = {
    __pageX: 0,
    __pageY: 0,

    //__colorIndex: 0,

    __loadedGeodataId: null,

    //__previousUrlTimeMarker: null,

    __cachedEl: null,// DOM elements cached references

    __blockUIOptions: null,
    __blockUIDefaultOptions: {
        header: 'Please wait',
        message: 'Operation in Progress...'
    },

    __initialize: function() {
        this.__appendInfoModalElToBody();
        this.__appendFileDownloadElToBody();

        this.__cachedEl = {
            infoModal: {
                modal: $('#info-modal'),
                header: $('#info-modal-header', this.modal),
                content: $('#info-modal-content', this.modal),
                initialized: false
            },

            fileDownload: $('#file-download-iframe')
        };

        this.formattingUtilities.__initialize(this);
    },

    blockUI: function(opts) {
        var __this = this;

        var options = null;
        if (this.isDefinedAndNotNull(opts)) {
            options = opts;

            if (this.isNotDefined(options.header) != null) {
                options.header = this.__blockUIDefaultOptions.header;
            }
            if (this.isNotDefined(options.message)) {
                options.message = this.__blockUIDefaultOptions.message;
            }
        } else {
            options = {
                header: this.__blockUIDefaultOptions.header,
                message: this.__blockUIDefaultOptions.message
            };
        }

        this.__blockUIOptions = options;

        var onBlockCallback = function() {
            var options = __this.__blockUIOptions;

            if (options != null && options.button != null) {
                // to unbind the previous handler
                options.__btnEl.unbind("click");
                options.__btnEl.click(function(e) {
                    if (options != null && options.button != null && options.button.callback != null) {
                        options.button.callback();
                    }
                });
            }
        };

        var str = '<div id="pleaseWaitAlert" class="alert alert-block alert-info fade in">' +
            //'<button type="button" class="close" data-dismiss="alert">&times;</button>' +
            '<h4 id="pleaseWaitAlert-header" class="alert-heading">' + options.header + '</h4>' +
            '<p id="pleaseWaitAlert-message">' + options.message + '</p>';
        if (options.button != null) {
            str += '<a id="pleaseWaitAlert-btn" href="#" class="btn margin-top-15px">' + options.button.label + '</a>';
        }
        str += '</div>';

        $.blockUI({
            message: str,
            css: {
                border: 'none',
                padding: '0',
                backgroundColor: 'transparent',
                opacity: 1.0
            },
            baseZ: 1050,
            onBlock: onBlockCallback
        });

        var el;

        el = options.__el = $('#pleaseWaitAlert');
        options.__elHeader = $('#pleaseWaitAlert-header', el);
        options.__elMessage = $('#pleaseWaitAlert-message', el);
        if (options.button != null) {
            options.__btnEl = $('#pleaseWaitAlert-btn', el);
        }

        //el.bind('close'/*'closed'*/, function () {
        //    $.unblockUI();
        //});
    },

    getBlockUIOptions: function() {
        return this.__blockUIOptions;
    },

    setBlockUIOptions: function(opts) {
        var options = this.__blockUIOptions;

        if (options != null) {
            this.copyProperties(opts, options);
        }/* else {
            el.data('options', opts);
        }*/

        options.__elHeader.html(options.header);
        options.__elMessage.html(options.message);
    },

    blockUIForMessage: function(header, message) {
        $.blockUI({
            message: '<div id="feedbackPanelAlert" class="alert alert-block alert-error fade in">' +
            '<button type="button" class="close" data-dismiss="alert">&times;</button>' +
            '<h4 class="alert-heading">' + header + '</h4>' +
            '<p id="pleaseWaitAlert-message">' + message + '</p>' +
            //'<p>' +
            //'<a class="btn btn-danger" href="#">Take this action</a> <a class="btn" href="#">Or do this</a>' +
            //'</p>' +
            '</div>',
            css: {
                //width: '800px',
                border: 'none',
                //top: '100px',
                //left: 'none',
                //margin: '0 auto',
                padding: '0',
                //position: 'relative',
                backgroundColor: 'transparent',
                opacity: 1.0
            },
            baseZ: 1050
        });
        $('#feedbackPanelAlert').bind('close'/*'closed'*/, function () {
            $.unblockUI();
        });
    },

    unblockUI: function() {
        $.unblockUI();

        this.__blockUIOptions = null;
    },

    showFeedbackPanelAlert: function(content) {
        var el = $(content);
        $('#feedbackPanelContent'/*, '#'*/).html(el);

        //$('#feedbackPanel-alert').alert();
        $('#feedbackPanel-alert').removeClass('hide');
        //this.blockUIFeedbackPanelAlert(content);
    },

    processFeedbackPanelAlert: function(feedbackPanelId) {
        var el = $('#' + feedbackPanelId), html;
        if ($.trim(html = el.html()).length > 0/*el.is(':not(:empty)')*/) {
            com.sci.logisticsmap.utilities.showFeedbackPanelAlert(html/*el.html()*/);
        }
    },

    toggleDropDown: function(callback) {
        $('.dropdown.open .dropdown-toggle').dropdown('toggle');
        if (typeof callback != 'undefined') {
            setTimeout(function() {
                callback();
            }, 100);
        }
    },

    isLocation: function(path) {
        var originalPath = location.pathname;
        return originalPath == (contextPath + path);
    },

    changeLocation: function(url) {
        location.href = url;
    },

    addContextPathToUrl: function(url) {
        return contextPath + url;
    },

    addTimeMarkerToUrl: function(url) {
        var timeMarker = new Date().getTime();
        /*if (this.__previousUrlTimeMarker != null && timeMarker == this.__previousUrlTimeMarker) {
            timeMarker += 1;
        }
        this.__previousUrlTimeMarker = timeMarker;*/
        return url + (url.indexOf('?') > -1 ? '&' : '?') + timeMarker;
    },

    addContextPathAndTimeMarkerToUrl: function(url) {
        return this.addTimeMarkerToUrl(this.addContextPathToUrl(url));
    },

    getColor: function() {return null;
        /*var color = constants.colors[this.__colorIndex];

        if (++this.__colorIndex >= constants.colors.length) {
            this.__colorIndex = 0;
        }

        return color;*/
    },

    padString: function(i) {
        return (i < 10) ? "0" + i : "" + i;
    },

    isEmptyMap: function(map) {
        for (var key in map) {
            return false;
        }
        return true;
    },

    isDefined: function(target) {
        return (typeof target != 'undefined');
    },

    isNotDefined: function(target) {
        return (typeof target == 'undefined');
    },

    isDefinedAndNotNull: function(target) {
        return (typeof target != 'undefined' && target != null);
    },

    isNotDefinedOrNull: function(target) {
        return (typeof target == 'undefined' || target == null);
    },

    copyProperties: function(opts, options) {
        for (var key in opts) {
            if (typeof opts[key] == 'object') {
                if (this.isNotDefinedOrNull(options[key])) {
                    options[key] = {};
                }
                this.copyProperties(opts[key], options[key]);
            } else {
                options[key] = opts[key];
            }
        }
    },

    getPageOffset: function() {
        return {top: this.__pageY, left: this.__pageX};
    },

    setLoadedGeodataId: function(loadedGeodataId) {
        this.__loadedGeodataId = loadedGeodataId;
    },

    onPageMouseMove: function(e) {
        this.__pageX = e.pageX;
        this.__pageY = e.pageY;
    },

    formattingUtilities: {
        DISTANCE_UNITS: {
            MILES: 1,
            KMS: 2
        },

        __distanceUnits: 0,

        __parent: null,

        __initialize: function(parent) {
            this.__parent = parent;

            this.__distanceUnits = this.DISTANCE_UNITS.MILES;
        },

        formatDate: function(d, format) {
            return $.format.date(d, format);
            /*var date = (typeof d == 'object') ? d : new Date(d);
            var ps = this.__parent.padString;
            var result = ps(date.getFullYear()) +
                    " " + ps(1 + date.getMonth()) +
                    " " + ps(date.getDate()) +
                    " " + ps(date.getHours()) +
                    ":" + ps(date.getMinutes()) +
                    ":" + ps(date.getSeconds());
            return result;*/
        },

        formatDistance: function(distance) {// distance in meters
            var distanceStr = '';
            if (this.__distanceUnits != 0) {
                var divider;
                var unitsStr;

                if (this.__distanceUnits == this.DISTANCE_UNITS.MILES) {
                    divider = 1609.34;
                    unitsStr = ' miles';
                } else if (this.__distanceUnits == this.DISTANCE_UNITS.KMS) {
                    divider = 1000;
                    unitsStr = ' kms';
                }

                var d = distance / divider;
                var dX10 = Math.round(d * 10);
                distanceStr = Math.floor(dX10 / 10) + '.' + (dX10 % 10) + unitsStr;
            }
            return distanceStr;
        },

        formatDuration: function(duration) {// duration in seconds
            var durationStr = '';
            if (duration > 0) {
                var dH = 0, dM = 0, dS = 0;

                dS = duration % 60;
                if (duration > 60) {// > 1 minute
                    dM = ((duration - dS) / 60) % 60;
                    if (duration > 3600) {// > 1 hour
                        dH = (duration - (dM * 60 + dS)) / 3600;
                    }
                }

                // seconds rounding
                if (duration < 30) {
                    dM = 1;
                } else if (dS >= 30) {
                    dM += 1;
                }

                durationStr += dH;
                durationStr += ':';
                if (dM < 10) {
                    durationStr += '0'
                }
                durationStr += dM;
            }
            return durationStr;
        }
    },

    openInfoModal: function(header, content) {
        var cachedModalEl = this.__cachedEl.infoModal;

        cachedModalEl.header.html(header);

        cachedModalEl.content.html(content);

        cachedModalEl.modal.modal('show');
        if (!cachedModalEl.initialized) {
            cachedModalEl.modal.on('hidden', function () {
                cachedModalEl.header.empty();
                cachedModalEl.content.empty();
            });

            cachedModalEl.modal.on('shown', function () {
            });

            cachedModalEl.initialized = true;
        }
    },

    downloadFile: function(url, callback) {
        var fileDownloadEl = this.__cachedEl.fileDownload;

        if (typeof callback == 'function') {
        //if (typeof callback != 'undefined') {
            fileDownloadEl.ready(function () {
                callback();

                setTimeout(function () {
                    fileDownloadEl.unbind('ready');
                }, 50);
            });
        }

        fileDownloadEl.attr('src', url);
    },

    __appendInfoModalElToBody: function() {
        var str = '<div id="info-modal" class="modal hide fade">'
                + '<div class="modal-header">'
                + '<button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>'
                + '<h4 id="info-modal-header">'
                + '&nbsp;'
                + '</h4>'
                + '</div>'
                + '<div class="modal-body">'
                + '<div id="info-modal-content"></div>'
                + '</div>'
                //+ '<div class="modal-footer">'
                //+ '<a href="#" class="btn btn-primary">Close</a>'
                //+ '</div>'
                + '</div>'
                ;

        $('body').append($(str/*, {
            id: 'info-modal' 
        }*/));
    },

    __appendFileDownloadElToBody: function() {
        var str = '<iframe id="file-download-iframe" style="display: none;">'
                + '</iframe>'
                ;

        $('body').append($(str/*, {
            id: 'download-iframe'
        }*/));
    }
};

$(document).ready(function() {
    com.sci.logisticsmap.utilities.__initialize();
});